package corp.sunny.commons.util.security;

import java.util.Map;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;

/**
 * @File:JAASLoginModule.java
 * @Date:Jun 10, 2011
 * @Author:Subhash Bavi
 * 
 * @Description:
 * @Copyright Sunny Corporation - 2011
 */
@SuppressWarnings("unused")
public abstract class JAASLoginModule implements LoginModule {

	protected Subject subject;
	private CallbackHandler callbackHandler;

	protected JAASPrincipal jaasPrincipal;
	protected JAASCallbackHandler jaasCallbackHandler = new JAASCallbackHandler("", "");

	@SuppressWarnings("rawtypes")
	private Map sharedState, options;

	/*
	 * Initiliaze's the LoginModule with necessary credential's
	 * 
	 * (non-Javadoc)
	 * 
	 * @see javax.security.auth.spi.LoginModule#initialize(javax.security
	 * .auth.Subject , javax.security.auth.callback.CallbackHandler,
	 * java.util.Map, java.util.Map)
	 */
	public void initialize(Subject subject, CallbackHandler callbackHandler,
			Map<String, ?> sharedState, Map<String, ?> options) {
		this.subject = subject;
		this.callbackHandler = callbackHandler;
		this.sharedState = sharedState;
		this.options = options;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.security.auth.spi.LoginModule#abort()
	 */
	public boolean abort() throws LoginException {
		jaasPrincipal = null;
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.security.auth.spi.LoginModule#logout()
	 */
	public boolean logout() throws LoginException {
		subject.getPrincipals().remove(jaasPrincipal);
		return true;
	}

	/**
	 * Method overloading
	 * 
	 */
	public boolean commit(String name, Object obj) throws LoginException {

		this.jaasPrincipal = new JAASPrincipal(name, obj);

		// Set the principal
		if (!this.subject.getPrincipals().contains(this.jaasPrincipal)) {
			this.subject.getPrincipals().add(this.jaasPrincipal);
		}
		return true;
	}
}
